import axios, { type AxiosResponse } from 'axios';

const dispatcherUrl = 'http://172.20.64.68:76'; // 服务器Dispatcher 服务地址
// const dispatcherUrl = 'http://10.215.58.251:76'; // 本机Dispatcher 服务地址

// 通用响应处理
const handleResponse = <T>(response: AxiosResponse<T>) => {
  const { method, url, data: requestData } = response.config;

  console.log(`[REST请求] 方法: ${method?.toUpperCase()}, URL: ${url}`);
  console.log(`[Body]`, requestData);

  console.log('请求成功:', JSON.stringify(response.data, null, '\t'));
  return response;
};

// 通用错误处理
const handleError = (error: any) => {
  console.error('请求失败:', error);
  throw error;
};

export const dispatcher = {
  startInstance: (
    para: { filePath?: string; fileId?: string; userName?: string; fawkesAuthToken?: string } = {},
  ) => {
    console.log(`请求在最佳服务器上启动新实例`);
    return axios
      .post(`${dispatcherUrl}/v1/instances/start`, para)
      .then(handleResponse)
      .catch(handleError);
  },

  getServersLoads: () => {
    console.log(`请求获取所有服务器负载`);
    return axios.get(`${dispatcherUrl}/v1/servers/loads`).then(handleResponse).catch(handleError);
  },

  getServersStatus: () => {
    console.log(`请求获取所有服务器实例统计信息`);
    return axios.get(`${dispatcherUrl}/v1/servers/status`).then(handleResponse).catch(handleError);
  },

  getInstances: (serverUrl: string) => {
    console.log(`请求获取服务器 ${serverUrl} 上的实例列表`);
    return axios
      .post(`${dispatcherUrl}/v1/servers/instances/list`, { serverUrl })
      .then(handleResponse)
      .catch(handleError);
  },

  stopInstance: (serverUrl: string, instanceId: string) => {
    console.log(`请求停止服务器 ${serverUrl} 上的实例 ${instanceId}`);
    return axios
      .post(`${dispatcherUrl}/v1/servers/instances/stop`, { serverUrl, instanceId })
      .then(handleResponse)
      .catch(handleError);
  },

  stopAllInstancesOnServer: (serverUrl: string) => {
    console.log(`请求停止服务器 ${serverUrl} 上的所有实例`);
    return axios
      .post(`${dispatcherUrl}/v1/servers/instances/stop-all`, { serverUrl })
      .then(handleResponse)
      .catch(handleError);
  },

  stopAllInstances: () => {
    console.log(`请求停止所有服务器上的所有实例`);
    return axios
      .post(`${dispatcherUrl}/v1/instances/stop-all`)
      .then(handleResponse)
      .catch(handleError);
  },
};
